package oop.ex1.filters;

import java.io.File;
import java.io.IOException;
import java.util.TreeSet;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

//###############
//FILE : NameFilter.java
//WRITER : Amir Wilf, wilfoa, 300007085
//WRITER : Daniel Acherkan, danithelion, 310116348
//EXERCISE : oop ex1 2011
//DESCRIPTION:
//A file filter which filter files by matching a pattern in the filename
//###############

public class NameFilter extends TextFilter {

	// *******
	// METHODS
	// *******
	/**
	 * Constructor for the class
	 * @param text the text to search for in file names
	 */
	public NameFilter(String text, boolean not) {
		super(text, not);
	}

	/**
	 * The filter function which employs the pattern to match on the list of
	 * files in the directory
	 * @param directoruPath The path in which the files to filter are
	 * @return A TreeSet of the resulted filtered files
	 */
	public TreeSet<File> filter(TreeSet<File> fullDirectoryFiles) {
		Matcher m;
		String fileName[] = null;
		TreeSet<File> list = new TreeSet<File>();
		for (File file : fullDirectoryFiles) {
			try {
				fileName = file.getCanonicalPath().split(SLASH);
				//search for the pattern in the file name only
				m = this._pattern.matcher(fileName[fileName.length - 1]);
				if (m.find()) {
					list.add(file);
				}
			} catch (IOException e) {
				System.exit(-1);
			}
		}
		return addNegation(list, fullDirectoryFiles);
	}

	/**
	 * This method parses the text into a RegEx pattern to match on the files
	 * to filter.
	 * @param text the text to search match files according to
	 */
	@Override
	protected void parsePattern(String text) {
		//substituting all /./ as to not confuse the matcher REGEX pattern
		String pattern = text.replaceAll(SUBSTITUTE + DOT, SUBSTITUTE
				+ SUBSTITUTE + DOT);
		//replacing all '*' in the REGEX pattern '.*'
		pattern = pattern.replaceAll(SUBSTITUTE + STAR, FIND_ALL);
		this._pattern = Pattern.compile(pattern);
	}
}
